// @flow

import React from 'react';
import PropTypes from 'prop-types';
import constant from './constant'

class Cell extends React.Component {
    constructor(props) {
        super(props);
    }

    onInputChange(e, rowIndex, columnIndex, key) {
        const value = e.target.value;
        this.props.onInputChange && this.props.onInputChange(value, rowIndex, columnIndex, key);
    }

    changeCellEditStatus(item, rowIndex, column, type) {
        console.log(type)
        this.props.changeCellEditStatus && this.props.changeCellEditStatus(item, rowIndex, column, type);
    }

    onBlur() {
        console.log('..')
    }

    render() {

        const columns = this.props.columns;
        const item = this.props.item;
        const rowIndex = this.props.rowIndex;

        return (
            <div>
                {
                    columns.map((column, index) => {
                        const value = item[column.key];
                        let cellContent = <span>{value}</span>;
                        console.log('item key:  ' + item.activeColumn);
                        if (item.activeColumn && item.activeColumn === column.key) {
                            cellContent = (
                                <input
                                    className="s-bs-table__content__td--edit" type="text"
                                    value={value}
                                    onChange={(e) => { this.onInputChange(e, rowIndex, index, column.key) }}
                                    onBlur={() => { this.changeCellEditStatus(item, rowIndex, column.key, constant.CELL_CANCEL) }} autoFocus
                                />
                            );
                        }
                        return (
                            <div style={{ width: column.width }} className="s-bs-table__content__td" onDoubleClick={() => { this.changeCellEditStatus(item, rowIndex, column.key, constant.CELL_EDIT) }} key={`${index}`}>
                                {
                                    value !== undefined &&
                                    cellContent
                                }
                            </div>
                        )
                    })
                }
            </div>
        );
    }
}

Cell.propTypes = {
    item: PropTypes.object.isRequired,
    rowIndex: PropTypes.number,
    columns: PropTypes.array.isRequired,
    onInputChange: PropTypes.func.isRequired,
    changeCellEditStatus: PropTypes.func,
}

export default Cell;
